package cn.javayong.aviatorscript.demo;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.apache.commons.codec.digest.DigestUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class MainApplication {

    public static BigDecimal getDiscount(BigDecimal amount, String rule) {
        // 执行规则并计算最终价格
        Map<String, Object> env = new HashMap<String, Object>();
        env.put("amount", amount);
        Expression expression = AviatorEvaluator.compile(
                DigestUtils.md5Hex(rule.getBytes()),
                rule,
                true);
        Object result = expression.execute(env);
        if (result != null) {
            return new BigDecimal(String.valueOf(result));
        }
        return null;
    }

    public static void main(String[] args) throws Exception {

        // step1 : 此处可以从配置中心 或者数据库中获取
        String rule = "if (amount>=1000){\n" +
                "    return 200;\n" +
                "}elsif(amount>=500){\n" +
                "    return 100;\n" +
                "}else{\n" +
                "    return 0;\n" +
                "}\n";

        // step 2: 通过 AviatorScript 执行
        BigDecimal discount = getDiscount(new BigDecimal("600"), rule);
        System.out.println("discount:" + discount);

    }

}
